package mysql

import (
	"gorm.io/gorm"
	"wms/models"
)

// GetFuncUrisByRoleIdentity 根据 role_identity 获取 function_basic 的 uris
func GetFuncUrisByRoleIdentity(roleIdentity string) (*gorm.DB, error) {
	// 1. 获取角色原生的 id，role_id
	var rbId int64
	tx := GetRoleBasicIdByIdentity(roleIdentity)
	if err := tx.Find(&rbId).Error; err != nil {
		return nil, err
	}

	// 2. 通过 role_id 在 role_function 连接 function_basic 表查找 uri
	tx1 := DB.Model(new(models.RoleFunction)).Select("fb.uri").
		Joins("LEFT JOIN function_basic fb ON fb.id = role_function.function_id").
		Where("role_function.role_id = ?", rbId)
	return tx1, nil
}

// GetFuncBasicByRoleIdentity 根据 role_identity 获取 function_basic 列表，包含 menu_id
func GetFuncBasicByRoleIdentity(roleIdentity string, isAdmin bool) (*gorm.DB, error) {
	if isAdmin {
		tx := DB.Model(new(models.FunctionBasic)).Select("*").Order("sort ASC")
		return tx, nil
	}
	// 1. 获取 role_id
	rb := new(models.RoleBasic)
	tx := GetRoleBasicIdByIdentity(roleIdentity)
	if err := tx.Find(rb).Error; err != nil {
		return nil, err
	}
	// 2. 关联 role_function 和 function_basic
	tx1 := DB.Model(new(models.RoleFunction)).Select("fb.id, fb.created_at, fb.updated_at, "+
		"fb.identity, fb.menu_id, fb.name, fb.uri, fb.sort").
		Joins("LEFT JOIN function_basic fb ON fb.id = role_function.function_id").
		Where("role_function.role_id = ?", rb.ID).Order("sort ASC")
	return tx1, nil
}

// GetFuncBasicWithMenuIdentityByRoleIdentity 根据 role_identity 获取 function_basic 列表，替换 menu_identity
func GetFuncBasicWithMenuIdentityByRoleIdentity(roleIdentity string, isAdmin bool) (*gorm.DB, error) {
	tx, err := GetFuncBasicByRoleIdentity(roleIdentity, isAdmin)
	if err != nil {
		return nil, err
	}
	if isAdmin {
		tx1 := tx.Select("function_basic.identity, mb.identity menu_identity, function_basic.name, function_basic.uri, " +
			"function_basic.sort").Joins("LEFT JOIN menu_basic mb ON mb.id = function_basic.menu_id")
		return tx1, nil
	}
	tx1 := tx.Select("fb.identity, fb.name, fb.sort, fb.uri, mb.identity menu_identity").
		Joins("LEFT JOIN menu_basic mb ON mb.id = fb.menu_id")
	return tx1, nil
}

// GetFuncIdsByMenuId 根据 menu_id 获取 function_basic 的原生 ids
func GetFuncIdsByMenuId(menuId uint) *gorm.DB {
	tx := DB.Model(new(models.FunctionBasic)).Select("id").Where("menu_id = ?", menuId)
	return tx
}

// GetFuncIdsByMenuIdCruds 根据 menuId 和 cruds 获取 function_basic 的原生 id
func GetFuncIdsByMenuIdCruds(menuId uint, cruds []int) *gorm.DB {
	tx := GetFuncIdsByMenuId(menuId).Where("crud IN ?", cruds)
	return tx
}

// GetFuncIdUrisByMenuIdCruds 根据 menuId 和 cruds 获取 function_basic 的原生 ids 及 uris
func GetFuncIdUrisByMenuIdCruds(menuId uint, cruds []int) *gorm.DB {
	tx := GetFuncIdsByMenuIdCruds(menuId, cruds).Select("id, uri")
	return tx
}

// CreateRoleFunc 插入用户所有权限进 role_function 表中
func CreateRoleFunc(roleFunc []*models.RoleFunction) error {
	return DB.Create(roleFunc).Error
}
